{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# <center>第4章 函数与函数编程</center>\n",
    "\n",
    "<br>\n",
    "\n",
    "- [4.1 函数的定义与调用](#4.1-函数的定义与调用)\n",
    "  - [4.1.1 函数的定义](#4.1.1-函数的定义)\n",
    "  - [4.1.2 函数的调用](#4.1.2-函数的调用)\n",
    "  - [4.1.3 变量的作用域](#4.1.3-变量的作用域)\n",
    "- [4.2 函数的参数](#4.2-函数的参数)\n",
    "  - [4.2.1 位置参数与关键字参数](#4.2.1-位置参数与关键字参数)\n",
    "  - [4.2.2 可选参数](#4.2.2-可选参数)\n",
    "  - [4.2.3 可变参数](#4.2.3-可变参数)\n",
    "  - [4.2.4 参数分配](#4.2.4-参数分配)\n",
    "- [4.3 函数的类型注解*](#4.3-函数的类型注解*)\n",
    "  - [4.3.1 类型注解](#4.3.1-类型注解)\n",
    "  - [4.3.2 `typing`模块](#4.3.2-typing模块)\n",
    "  - [4.3.3 类型注解的使用](#4.3.3-类型注解的使用)\n",
    "- [4.4 函数对象](#4.4-函数对象)\n",
    "  - [4.4.1 一等对象](#4.4.1-一等对象)\n",
    "  - [4.4.2 Python函数的面向对象特征](#4.4.2-Python函数的面向对象特征)\n",
    "  - [4.4.3 Python函数的一等对象特征](#4.4.3-Python函数的一等对象特征)\n",
    "- [4.5 嵌套函数与闭包](#4.5-嵌套函数与闭包)\n",
    "  - [4.5.1 嵌套函数](#4.5.1-嵌套函数)\n",
    "  - [4.5.2 闭包](#4.5.2-闭包)\n",
    "- [4.6 函数装饰器](#4.6-函数装饰器)\n",
    "  - [4.6.1 简单函数装饰器](#4.6.1-简单函数装饰器)\n",
    "  - [4.6.2 函数装饰器的工作原理](#4.6.2-函数装饰器的工作原理)\n",
    "  - [4.6.3 函数装饰器的优化](#4.6.3-函数装饰器的优化)\n",
    "  - [4.6.4 装饰器的叠加*](#4.6.4-装饰器的叠加*)\n",
    "  - [4.6.5 含参装饰器](#4.6.5-含参装饰器)\n",
    "  - [4.6.6 函数装饰器应用实例 *](#4.6.6-函数装饰器应用实例-*)\n",
    "  - [4.6.7 重要的 Python 内置装饰器 *](#4.6.7-重要的-Python-内置装饰器-*)\n",
    "- [4.7 常用函数编程工具*](#4.7-常用函数编程工具*)\n",
    "  - [4.7.1 常用工具函数](#4.7.1-常用工具函数)\n",
    "  - [4.7.2 `operator`模块](#4.7.2-operator模块)\n",
    "  - [4.7.3 `itertools`模块](#4.7.3-itertools模块)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "###  4.1.1 函数的定义\n",
    "\n",
    "- 函数的作用\n",
    "  - 是实现结构化编程的重要工具之一\n",
    "  - 把需要重复使用的具有相对独立的功能部分定义为函数\n",
    "\n",
    "- 定义要点\n",
    "  - 函数的核心组成部分包括函数名、函数的参数列表、函数的返回值\n",
    "  - 函数的参数列表也称为函数的签名\n",
    "  - 函数的文档字符串也是函数的组成部分（非必须），属性名为`__doc__`\n",
    "  - 使用`def`关键字来定义函数\n",
    "  - 函数使用`return`语句返回运行结果，如果没有`return`语句函数会返回`None`\n",
    "\n",
    "\n",
    "```python\n",
    "def 函数名(参数列表):\n",
    "    \"\"\"文档字符串\"\"\"\n",
    "    函数体\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "def add(x, y):\n",
    "    \"\"\"\n",
    "    数值求和.\n",
    "    Args:\n",
    "        x: 第一个参数.\n",
    "        y: 第二个参数.\n",
    "    Returns: 两个参数之和.\n",
    "    \"\"\"\n",
    "    s = x + y\n",
    "    return s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "    数值求和.\n",
      "    Args:\n",
      "        x: 第一个参数.\n",
      "        y: 第二个参数.\n",
      "    Returns: 两个参数之和.\n",
      "    \n"
     ]
    }
   ],
   "source": [
    "print(add.__doc__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 函数的副作用\n",
    "  - 函数的副作用是指函数除了返回值之外，还对环境产生了附加的影响\n",
    "  - 函数的副作用往往会为程序设计带来不必要的麻烦，因此应当尽可能减少\n",
    "- 尽可能遵循的原则\n",
    "  - 在定义函数的时候尽可能让函数仅仅通过参数与返回值与环境产生联系\n",
    "    - 函数只应当有一个入口，就是其参数；\n",
    "    - 函数只应当有一个出口，就是`return`语句。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 函数可以定义在什么地方？\n",
    "  - 模块\n",
    "  - 其他函数之中\n",
    "  - 类的方法之中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fun():\n",
    "    def inner_fun():\n",
    "        print('This is inner fun!')\n",
    "    print('This is fun!')\n",
    "    inner_fun()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.1.2 函数的调用\n",
    "\n",
    "- 参数传递\n",
    "  - 通过函数的名字来调用函数\n",
    "  - 调用其他函数的函数，称为主调函数\n",
    "    - 如果函数中定义了参数，在主调函数中还应当传入对应的参数\n",
    "  - 定义在参数列表中的参数，称为函数的__形参__（formal parameter）\n",
    "  - 由主调函数传入的参数，称为__实参__（actual parameter）\n",
    "  - 形参变量和实参变量的命名可以不同，在函数调用的过程中，实参会将其值传递给形参"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "n1 = 2\n",
    "n2 = 3\n",
    "add(n1, n2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "  - 形参与实参是相互独立的，改变形参的值并不会导致实参的值被改变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fun(formal_p):\n",
    "    formal_p = [8, 5, 7]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 2]\n"
     ]
    }
   ],
   "source": [
    "actual_p = [1, 4, 2]\n",
    "fun(actual_p)\n",
    "print(actual_p) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "  - 如果参数传递的是可变数据类型，形参传递给实参的实际上是可变数据的引用\n",
    "  - 形参引用的改变不会导致实参引用发生变化，但是由于它们指向相同的数据，因此形参指向的数据被改变后实参所指向的数据当然也会被改变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fun(formal_p):\n",
    "    formal_p[0] = 0 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 4, 2]\n"
     ]
    }
   ],
   "source": [
    "actual_p = [1, 4, 2]\n",
    "fun(actual_p)\n",
    "print(actual_p)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 递归调用\n",
    "  - 函数定义之后，允许其他函数调事，也允许自己调用自己\n",
    "  - 函数调用了自身称为__递归调用__，这样的函数称为__递归函数__\n",
    "  - 递归函数中一定要有退出递归的条件，否则就会陷入无限的递归循环之中"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 利用递归实现列表的深复制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "def copy(seq):\n",
    "    return [copy(o) if type(o) is list else o for o in seq]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, [3, 4, [5, 6, [7, 8, [9, 10, 11]]]]]\n",
      "[1, 2, [3, 4, [5, 6, [7, 8, [9, 10, 0]]]]]\n"
     ]
    }
   ],
   "source": [
    "lst = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10, 11]]]]]\n",
    "lst_new = copy(lst)\n",
    "lst_new[2][2][2][2][2] = 0\n",
    "print(lst)\n",
    "print(lst_new)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.1.3 变量的作用域\n",
    "\n",
    "- 全局变量\n",
    "  - 全局变量是直接在模块中定义的变量，其作用域为定义变量的位置直至模块结束\n",
    "  - 定义在一个模块中的全局变量可以在其它模块中利用`import`语句导入使用\n",
    "  - 全局变量应当定义在模块的头部，以利用管理和维护\n",
    "  - 在模块中修改全局变量的值与在函数中修改参数的值相似\n",
    "    - 模块中修改了其他模块中定义的全局变量的引用，则其他模块中所读取到的全局变量的值不会发生变化\n",
    "    - 如果改变了引用所指向的数据，则其他模块中读取到的全局变量所指向的数据也会改变"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 局部变量\n",
    "  - 定义在函数中的局部变量其作用范围是其定义的位置开始至函数结束\n",
    "  - 定义在类方法中的变量也是局部变量（参见面向对象编程部分）\n",
    "  - 在推导式中（包括列表推导式、生成器推导式、集合推导式和字典推导式）中定义的变量，其作用范围仅限于推导式内部"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `global`语句\n",
    "  - 在函数中定义全局变量\n",
    "    - 定义在函数中的全局变量，只有在函数执行之后才能被使用\n",
    "    - 全局变量能够起到减少函数参数数量、简化代码的作用，但是它破坏了函数只有一个入口和一个出口的原则，因此应当尽可能减少使用\n",
    "    - 要避免使用定义在函数中的全局变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 1\n",
    "def fun():\n",
    "    global x\n",
    "    x = 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "fun()\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "   - 利用`global`将局部变量声明为全局变量\n",
    "     - 在函数内部能够访问全局变量，但是不能修改全局变量的取值\n",
    "     - 如果尝试在函数中修改全局变量的值，则相当于重新定义了一个同名的局部变量\n",
    "     - 使用`global`可以将局部变量声明为同名的全局变量，就可以对其进行修改了"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "0\n"
     ]
    }
   ],
   "source": [
    "x = 0\n",
    "def fun():\n",
    "    x = 1\n",
    "    print(x)\n",
    "    \n",
    "fun()\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "1\n"
     ]
    }
   ],
   "source": [
    "x = 0\n",
    "def fun():\n",
    "    global x\n",
    "    x = 1\n",
    "    print(x)\n",
    "\n",
    "fun()\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## 4.2 函数的参数\n",
    "\n",
    "### 4.2.1 位置参数与关键字参数\n",
    "\n",
    "- 位置参数：实参列表中的参数将数值传递给形参列表中相同位置的参数。这种方式也是我们最常接触到的参数传递方式\n",
    "- 关键字参数：也称为命名参数，在参数传递时，实参利用形参变量的名将值传递给指定形参"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "def say(greeting, describe, target):\n",
    "    print(f'{greeting} {describe} {target}!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello beautiful Python!\n",
      "Hello beautiful Python!\n"
     ]
    }
   ],
   "source": [
    "say('Hello', 'beautiful', 'Python')                           # 位置参数\n",
    "say(target='Python', greeting='Hello', describe='beautiful')  # 关键字参数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 调用函数时也可以混合使用位置参数和关键字参数，但是要求所有位置参数必须出现在关键字参数之前"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello beautiful Python!\n"
     ]
    }
   ],
   "source": [
    "say('Hello', target='Python', describe='beautiful')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "positional argument follows keyword argument (<ipython-input-18-33a91a139779>, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-18-33a91a139779>\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m    say(greeting='Hello', 'beautiful', 'Python')\u001b[0m\n\u001b[1;37m                         ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m positional argument follows keyword argument\n"
     ]
    }
   ],
   "source": [
    "say(greeting='Hello', 'beautiful', 'Python')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 使用位置参数时要求实参和形参的顺序必须一致\n",
    "- 使用关键字参数时，实参的顺序是无所谓的，只要正确指定形参名即可\n",
    "- 在定义函数时，可以指定一部分参数在调用时必须使用关键字参数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 强制关键字参数\n",
    "  - 形参列表中可使用一个特殊的元素`*`，表示位于它左侧的参数在调用时可以使用位置参数也可以使用关键字参数；但位于它右侧的参数必须使用关键字参数，因此称为__强制关键字参数__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello beautiful Python!\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "say() takes 2 positional arguments but 3 were given",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-19-7a9dfada02dc>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[0msay\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'Hello'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'beautiful'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mtarget\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'Python'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[0msay\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'Hello'\u001b[0m\u001b[1;33m,\u001b[0m  \u001b[1;34m'beautiful'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'Python'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: say() takes 2 positional arguments but 3 were given"
     ]
    }
   ],
   "source": [
    "def say(greeting, describe, *, target):\n",
    "    print(f'{greeting} {describe} {target}!')\n",
    "    \n",
    "say('Hello', 'beautiful', target='Python')\n",
    "say('Hello',  'beautiful', 'Python')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 强制位置参数\n",
    "  - 形参列表中可使用一个特殊元素`/`，表示位于它左侧的参数在调用时必须使用位置参数\n",
    "\n",
    "- 下例中，参数`greeting`必须使用位置参数，`target`必须使用关键字参数，`describe`可以使用位置参数也可以使用关键字参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "def say(greeting, /, describe, *, target):\n",
    "    print(f'{greeting} {describe} {target}!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.2.2 可选参数\n",
    "\n",
    "- 定义函数的时候可以指定参数的默认值，有默认值的参数称为可选参数\n",
    "- 在调用的时候\n",
    "    - 如果实参列表中没有给出可选参数的值，则函数体中会使用默认值进行计算\n",
    "    - 如果实参列表中给出可选参数的值，则其默认值会被覆盖掉"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello beautiful Python!\n",
      "Hello powerful Python!\n"
     ]
    }
   ],
   "source": [
    "def say(greeting, describe='beautiful', target='Python'):\n",
    "    print(f'{greeting} {describe} {target}!')\n",
    "    \n",
    "say('Hello')\n",
    "say('Hello', 'powerful')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 在函数定义中可选参数必须出现在所有非可选参数之后"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "non-default argument follows default argument (<ipython-input-23-3c50971decba>, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-23-3c50971decba>\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m    def say(greeting='Hello', describe, target):\u001b[0m\n\u001b[1;37m           ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m non-default argument follows default argument\n"
     ]
    }
   ],
   "source": [
    "def say(greeting='Hello', describe, target):\n",
    "    print(f'{greeting} {describe} {target}!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "###  4.2.3 可变参数\n",
    "\n",
    "- 可变参数是指在函数调用时，实参的数量是不确定的，可以根据需要任意变化\n",
    "- 两种可变参数\n",
    "  - `*`修饰的参数用于收集实参中的位置参数\n",
    "    - 可变的位置参数被构建为一个元组\n",
    "  - `**`修饰的参数用于收集实参中的关键字参数\n",
    "    - 可变的关键字参数则被构建为一个字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def say(greeting='Hello', *describe):\n",
    "    print(type(describe))\n",
    "    print(f'{greeting} {\" and \".join(describe)} Python!')    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'tuple'>\n",
      "Hello beautiful and powerful and easy Python!\n"
     ]
    }
   ],
   "source": [
    "say('Hello', 'beautiful', 'powerful', 'easy')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `*`修饰的参数可位于形参列表的任意位置，但是它右侧的参数在调用时必须使用关键字参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "def say(greeting, *describe, target):\n",
    "    print(f'{greeting} {\" and \".join(describe)} {target}!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello beautiful and powerful and easy Python!\n"
     ]
    }
   ],
   "source": [
    "say('Hello', 'beautiful', 'powerful', 'easy', target='Python')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `**`修饰的参数必须位置于形参列表的最后\n",
    "- 可同时使用`*`和`**`来收集可变数量的位置参数和关键字参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "def say(greeting, *describe, **detail):\n",
    "    print(type(describe), type(detail))\n",
    "    print(f'{greeting} {\" and \".join(describe)} Python!')\n",
    "    details = [f\"It's {k} is {v}.\" for k, v in detail.items()]\n",
    "    print(' '.join(details))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'tuple'> <class 'dict'>\n",
      "Hello beautiful and powerful and easy Python!\n",
      "It's syntax is elegant. It's code is simple.\n"
     ]
    }
   ],
   "source": [
    "say('Hello', 'beautiful', 'powerful', 'easy', syntax='elegant', code='simple')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.2.4 参数分配\n",
    "\n",
    "- 在函数调用时，使用这`*`或`**`构造实参列表\n",
    "  - `*`用于将序列或元组拆解开来分配给形参中的位置参数\n",
    "  - `**`用于将字典拆解开来分配给形参中的关键字参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello beautiful Python!\n",
      "Hello beautiful Python!\n"
     ]
    }
   ],
   "source": [
    "def say(greeting, describe, target):\n",
    "    print(f'{greeting} {describe} {target}!')\n",
    "    \n",
    "para_tuple = ('Hello', 'beautiful', 'Python')\n",
    "say(*para_tuple)\n",
    "\n",
    "para_dict = {'greeting': 'Hello', 'describe': 'beautiful', 'target': 'Python'}\n",
    "say(**para_dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## 4.3 函数的类型注解*\n",
    "\n",
    "### 4.3.1 类型注解\n",
    "- 函数的类型注解功能最早出现在Python 3.5中\n",
    "- 与变量的类型注解相同，函数的类型注解也只是一种提示信息，主要为了提高代码的可读性、自动化文档生成、为开发工具提供方便等"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 函数的类型注解语法\n",
    "\n",
    "  `def func(arg: type, optarg: type = default) -> return_type:`\n",
    "  - `arg`：形参名；\n",
    "  - `type`：形参的类型；\n",
    "  - `optarg`：可选参数；\n",
    "  - `default`：默认值；\n",
    "  - `return_type`：返回值的类型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "def add(x: int, y: int) -> int:\n",
    "    return x + y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "2.0\n"
     ]
    }
   ],
   "source": [
    "print(add(1, 1))\n",
    "print(add(1.0, 1.0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- 添加了类型注解的函数，可以使用`__annotations__`属性来查看注解信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}\n"
     ]
    }
   ],
   "source": [
    "print(add.__annotations__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `mypy`\n",
    "  - Python解释器不会利用函数的类型注解来检查参数的类型，但是它们可以被一些第三方编译工具利用\n",
    "  - mypy就是一个静态类型版本的Python实现\n",
    "    - 提供了一个基于CPython的编译器mypyc，它能够像静态语言那样先将Python代码编译为二进制文件，从而提高程序的运行效率\n",
    "  - `pip install mypy`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "将下面的代码保存为名为add.py的文件："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.0"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def add(x: int, y: int) -> int:\n",
    "    return x + y \n",
    "add(1.0, 1.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "利用mypy来执行，它显示出函数`add`的两个实参数值与形参的类型不匹配的错误。\n",
    "\n",
    "```\n",
    "$ mypy add.py\n",
    "add.py:3: error: Argument 1 to \"add\" has incompatible type \"float\"; expected \"int\"\n",
    "add.py:3: error: Argument 2 to \"add\" has incompatible type \"float\"; expected \"int\"\n",
    "Found 2 errors in 1 file (checked 1 source file)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.3.2 `typing`模块\n",
    "\n",
    "- 对于一些复杂的数据类型，如`list`、`tuple`、`set`、`dict`等，类型注解并不能完全反映变量的结构\n",
    "- 例：\n",
    "  - 下面的函数中，参数`nums`注解为一个`list`，但是`nums`中究为什么类型的数值并不确定，需要添加更为细节的信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def average(nums:list) -> float:\n",
    "    n = len(nums)\n",
    "    return sum(nums)/n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- `typing`模块中提供了一些辅助类型，能够为类型添加更具体的注解信息"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `typing.List`\n",
    "  - 利用`typing`中的类型`List`可以将上例改写为如下形式，将参数`nums`注解为一个元素为`float`的列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4.5"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from typing import List\n",
    "def average(nums:List[float]) -> float:\n",
    "    n = len(nums)\n",
    "    return sum(nums)/n\n",
    "average([1.0, 4.0, 2.0, 8.0, 5.0, 7.0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- `typing.List`也可以嵌套使用，例如`data: List[List[int]]=[[1, 4], [2, 8], [5, 7]]`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `typing.Tuple`\n",
    "  - 由于`tuple`是不可变类型，因此可以为其每个元素添加类型注解"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('张三', 18, '男')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from typing import Tuple\n",
    "def create_student(name: str, age:int, gender:str) -> Tuple[str, int, str]:\n",
    "    return (name, age, gender)\n",
    "create_student('张三', 18, '男')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `typing.Sequence`\n",
    "  - 有时候函数的参数需要一个序列类型，`list`、`tuple`、`str`都可以，则可以使用`tying.Sequence`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Sequence\n",
    "def average(nums: Sequence[int]) -> float:\n",
    "    n = len(nums)\n",
    "    return sum(nums)/n\n",
    "average([1, 4, 2, 8, 5, 7])\n",
    "average((1, 4, 2, 8, 5, 7))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `typing.Union`\n",
    "  - 当变量类型可以是多种类型中的一种时，可以使用`typing.Union`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Sequence, Union\n",
    "def average(nums: Union[Sequence[int], Sequence[float]]) -> float:\n",
    "    n = len(nums)\n",
    "    return sum(nums)/n\n",
    "average([1.0, 4.0, 2.0, 8.0, 5.0, 7.0])\n",
    "average((1, 4, 2, 8, 5, 7))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `typing.Any`\n",
    "  - `typing.Any`表示变量可以是任意类型，下面的函数中参数`seq`被标注为元素类型任意的序列，返回值类型也是如此"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Sequence, Any\n",
    "def reverse(seq: Sequence[Any]) -> Sequence[Any]:\n",
    "    return seq[-1::-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `typing.Optional`\n",
    "  - `typing.Optional`表示变量可以是指定的类型或者`None`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Union, Optional\n",
    "def div(dividend: Union[int, float], divisor: Union[int, float]) -> Optional[float]:\n",
    "    if divisor == 0:\n",
    "        return None\n",
    "    else: \n",
    "        return dividend/divisor"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "  - `Optional[float]`与`Union[float, None]`等价"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `typing.NoReturn`\n",
    "  - `typing.NoReturn`表示函数中没有返回值，包括显式（`Return`）或隐式（函数默认返回`None`）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import NoReturn\n",
    "def error(info: str) -> NoReturn:\n",
    "    raise Exception(info)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `typing`模块中的其他常用类型\n",
    "\n",
    "\n",
    "|类型| 描述|\n",
    "|--|--|\n",
    "|`typing.Dict`| 字典|\n",
    "|`typing.Set`| 集合|\n",
    "|`typing.Generator`| 生成器|\n",
    "|`typing.Iterator`|迭代器|\n",
    "|`typing.Callable`| 可调用类型|"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "###  4.3.3 类型注解的使用\n",
    "\n",
    "- 类型注解在Python代码的运行过程中不起任何作用，使用与否不会对代码的功能产生影响。\n",
    "- 什么情况下应该使用类型注解呢？\n",
    "  - 初学者暂时不必考虑使用类型注解；\n",
    "  - 在很短的代码模块中使用注解的意义不大；\n",
    "  - 若是为了开发供他人使用的工具包，最好使用类型注解；\n",
    "  - 较大的软件项目中要使用类型注解。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## 4.4 函数对象\n",
    "\n",
    "### 4.4.1 一等对象\n",
    "\n",
    "- 面向对象编程中的对象\n",
    "  - 具有能够区别于其他所有对象或数值的唯一标识\n",
    "  - 每个对象都有至少一个“类型”\n",
    "  - 具有可供访问的属性和可供调用的方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 一等对象（First-class object）\n",
    "  - 一等对象可以是任何程序中的实体，而不一定是面向对象程序设计所指的“对象”\n",
    "  - 特征\n",
    "    - 可以被赋值给变量，或者作为数据结构的元素；\n",
    "    - 可以作为参数传递给其他函数；\n",
    "    - 可以作为函数的返回值；\n",
    "    - 能够在程序运行期间动态创建。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- Python中数值、列表、字典、集合等都是一等对象\n",
    "- 面向对象中的“对象”也是一等对象\n",
    "- 而函数则比较特殊，在不同的语言中差别很大\n",
    "  - C语言和C++语言中的函数不是一等对象，因为它们不能在运行中动态创建，必须在程序设计时在代码中确定下来\n",
    "  - Java和C#中本质上没有函数只有方法，所有的方法必须隶属于某一个类或对象\n",
    "  - Python和Javascript中，函数是一等对象"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.4.2 Python函数的面向对象特征\n",
    "\n",
    "- 每个函数都具有一个唯一的标识"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fun1():\n",
    "    pass\n",
    "\n",
    "def fun2():\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4520867008 4520868304\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "print(id(fun1), id(fun2))\n",
    "print(id(fun1) == id(fun2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- Python函数的类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "function"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(fun1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "function"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(fun2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- Python函数的属性和方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fun():\n",
    "     \"\"\"This is doc string of the function\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'This is doc string of the function'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fun.__doc__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['__repr__',\n",
       " '__call__',\n",
       " '__get__',\n",
       " '__new__',\n",
       " '__closure__',\n",
       " '__doc__',\n",
       " '__globals__',\n",
       " '__module__',\n",
       " '__code__',\n",
       " '__defaults__',\n",
       " '__kwdefaults__',\n",
       " '__annotations__',\n",
       " '__dict__',\n",
       " '__name__',\n",
       " '__qualname__',\n",
       " '__hash__',\n",
       " '__str__',\n",
       " '__getattribute__',\n",
       " '__setattr__',\n",
       " '__delattr__',\n",
       " '__lt__',\n",
       " '__le__',\n",
       " '__eq__',\n",
       " '__ne__',\n",
       " '__gt__',\n",
       " '__ge__',\n",
       " '__init__',\n",
       " '__reduce_ex__',\n",
       " '__reduce__',\n",
       " '__subclasshook__',\n",
       " '__init_subclass__',\n",
       " '__format__',\n",
       " '__sizeof__',\n",
       " '__dir__',\n",
       " '__class__']"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fun.__dir__()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.4.3 Python函数的一等对象特征\n",
    "\n",
    "- 函数赋值\n",
    "  - Python中可以将函数赋值给一个变量，而被赋值的变量能够像函数一样被调用\n",
    "  - 也作为一个数据结构的元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "def say(greeting, describe, target):\n",
    "    print(f'{greeting} {describe} {target}!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello beautiful python!\n"
     ]
    }
   ],
   "source": [
    "new_say = say\n",
    "new_say('Hello', 'beautiful', 'python')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "def fun1():\n",
    "    print('fun1')\n",
    "def fun2():\n",
    "    print('fun2')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "fun1\n",
      "fun2\n"
     ]
    }
   ],
   "source": [
    "fun_list = [fun1, fun2]\n",
    "for f in fun_list:\n",
    "    f()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 高阶函数\n",
    "  - 能够接收函数作为参数，或者返回值为函数的函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add(x, y):\n",
    "    return x + y\n",
    "\n",
    "def subtract(x, y):\n",
    "    return x - y\n",
    "\n",
    "def compute(x, y, fun):\n",
    "    return fun(x, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "compute(1, 1, add)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "compute(1, 1, subtract)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `sorted`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sort_key(e):\n",
    "    return e[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(1, 4), (5, 7), (2, 8)]"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lst = [(1, 4), (2, 8), (5, 7)]\n",
    "sorted(lst, key=sort_key)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 匿名函数\n",
    "  - `lambda`表达式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(1, 4), (5, 7), (2, 8)]"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lst = [(1, 4), (2, 8), (5, 7)]\n",
    "sorted(lst, key=lambda e: e[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- 特点\n",
    "  - `lambda`表达式的函数体中不能赋值，也不能使用`if`、`for`等流程控制语句，以及`return`语句\n",
    "  - `lambda`表达式在Python中基本上只用于作为函数参数使用，一般情况下仅包含一个表达式\n",
    "  - 用`lambda`表达式实现复杂的函数功能会影响代码的可读性，这种情况下最好使用`def`定义一个一般的函数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 动态创建函数\n",
    "  - 函数在程序运行过程中动态地创建出来"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "f_str = '''\n",
    "def dynamic_fun():\n",
    "    print('Hello dynamic function')\n",
    "\n",
    "'''\n",
    "exec(f_str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello dynamic function\n"
     ]
    }
   ],
   "source": [
    "dynamic_fun()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 使用`types.FunctionType`动态创建函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "import types\n",
    "fun_str = '''\n",
    "def dynamic_fun():\n",
    "    print('Hello dynamic Python!')\n",
    "'''\n",
    "\n",
    "code_obj = compile(fun_str, filename='', mode='exec')  # mode: 'exec'、'eval'或'single'\n",
    "fun = types.FunctionType(code_obj.co_consts[0], globals())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello dynamic Python!\n"
     ]
    }
   ],
   "source": [
    "fun()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## 4.5 嵌套函数与闭包\n",
    "\n",
    "### 4.5.1 嵌套函数\n",
    "- 嵌套函数是指一个函数（外部函数）中定义了另一个函数（内部函数）\n",
    "  - 是一种动态创建函数的方法\n",
    "  - 内部函数只能在外部函数中使用\n",
    "  - 有一定程度的“封装”作用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def outer():\n",
    "    def inner():\n",
    "        print(\"This is from inner\")\n",
    "    print(\"This is from outer\")\n",
    "    inner()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is from outer\n",
      "This is from inner\n"
     ]
    }
   ],
   "source": [
    "outer()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "#### `nonlocal`\n",
    "\n",
    "- 外部函数中定义的变量相当于其内部的全局变量，在内部函数中能够访问但不能修改\n",
    "- 使用`nonlocal`在内部函数中将变量称为非局部变量，就能够对其进行修改了"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def outer():\n",
    "    x = 0\n",
    "    def inner():\n",
    "        nonlocal x\n",
    "        x = 1\n",
    "    inner()\n",
    "    print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "outer()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `nonlocal`只能声明外部函数中已定义的变量为非局部变量。若内部函数中声明了外部未定义的变量，则会抛出错误"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "no binding for nonlocal 'x' found (<ipython-input-6-a818351f88c3>, line 3)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  File \u001b[0;32m\"<ipython-input-6-a818351f88c3>\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m    nonlocal x\u001b[0m\n\u001b[0m    ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m no binding for nonlocal 'x' found\n"
     ]
    }
   ],
   "source": [
    "def outer():\n",
    "    def inner():\n",
    "        nonlocal x\n",
    "        x = 0\n",
    "    inner()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### 4.5.2 闭包\n",
    "\n",
    "#### 概念与原理\n",
    "\n",
    "- 闭包是指引用了自由变量的函数\n",
    "  - 自由变量：是指被函数所使用，但是不在函数中定义，而是在函数运行的上下文中定义的变量\n",
    "- 闭包是引用了自由变量的函数，以及它们共同存在的上下文所组成的一个相对独立的实体"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 构成闭包的三个条件\n",
    "  - 定义了一个嵌套函数\n",
    "  - 内部函数中引用了外部函数中定义的变量\n",
    "  - 返回值是内部函数的引用"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 利用闭包实现累积求均值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "def create_averager():\n",
    "    numbers = []\n",
    "    def avg(nums):\n",
    "        if isinstance(nums, list):\n",
    "            numbers.extend(nums)\n",
    "        else:\n",
    "            numbers.append(nums)\n",
    "        return sum(numbers)/len(numbers)\n",
    "    return avg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "averager = create_averager()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4.0"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "averager([3, 5])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.0"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "averager(7)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6.4"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "averager([8, 9])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 闭包的运行原理\n",
    "  - 普通函数调用的特点\n",
    "    - 会在栈上压入函数的参数及函数中定义的局部变量，构建执行环境\n",
    "    - 函数执行完毕返回时，运行环境会被销毁，参数与局部变量也将不复存在\n",
    "    - 再次调用函数会生成新的环境\n",
    "  - 闭包的不同之处\n",
    "    - 外部函数在返回的时候，局部变量作为自由变量被内部函数所引用\n",
    "    - 内部函数被作为闭包返回至外部环境\n",
    "    - 闭包被销毁之前，它对外部函数中定义的自由变量的引用始终存在，因而自由变量不会被销毁\n",
    "    - 自由变量成为一种特殊的存在，它即不是全局变量，也不是局部变量\n",
    "  - 闭包的根本作用\n",
    "    - 利用一种特殊的方式延伸了变量的作用范围"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "#### 闭包的使用要点\n",
    "\n",
    "- 闭包并非由嵌套函数定义，而是通过调用外层函数创建出来\n",
    "- 每次调用都会创建出新的闭包\n",
    "- 不同的闭包之间是相互独立的，它们各自有着自己的自由变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "averager1 = create_averager()\n",
    "averager2 = create_averager()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4.0"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "averager1([3, 5])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.0"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "averager2([4, 6])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 利用闭包的`__code__`属性，可以查看局部变量和自由变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('numbers',)"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "averager.__code__.co_freevars"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('nums',)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "averager.__code__.co_varnames"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 自由变量的值，保存在`__closure__`属性之中，它是一个元素为`cell`对象的元组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 5, 7, 8, 9]"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "averager.__closure__[0].cell_contents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 当嵌套函数的外部函数中定义了多个内部函数并返回它们，并且它们引用了相同的自由变量，那么返回的函数和自由变量处于同一个闭包之中，共享相同的自由变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_averagers():\n",
    "    numbers = []\n",
    "    def avg1(num):\n",
    "        numbers.append(num)\n",
    "        return sum(numbers)/len(numbers)\n",
    "    def avg2(num):\n",
    "        numbers.append(num)\n",
    "        return sum(numbers)/len(numbers)\n",
    "    return avg1, avg2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "averager1, averager2 = create_averagers()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.0"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "averager1(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4.0"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "averager2(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "#### 实例\n",
    "\n",
    "##### 利用闭包实现任意一元函数\n",
    "\n",
    "一元$n$次函数可写为：\n",
    "$$\n",
    "f(x) = p_0x^n + p_1x^{n-1} + p_2 x^{n-2} + \\cdots + p_{n-1}x + p_{n}\n",
    "$$\n",
    "给定一组参数$p=(p_0,p_1,p_2,\\cdots,p_n)$就确定了一个一元函数。下面的例子中，外层函数接收定义一元函数的参数$p$，返回一个由该参数确定的一元函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "def create_univariate_func(*prams):\n",
    "    def univariate_func(x):\n",
    "        y = 0\n",
    "        order = len(prams) - 1\n",
    "        for i, p in enumerate(prams):\n",
    "            y += p * x**(order - i)\n",
    "        return y\n",
    "    return univariate_func"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "当参数为$p=(1,2,3)$时，定义的一元函数为$f(x) = x^2+2x+3$。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "uni_func = create_univariate_func(1, 2, 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "uni_func(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "uni_func(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "18"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "uni_func(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## 4.6 函数装饰器\n",
    "\n",
    "- 装饰器(Decorator)是用于修饰函数、类或者方法的一种特殊的工具，它能够在不 侵入代码的情况下增加或者改变修饰目标的功能\n",
    "  - 利用函数实现\n",
    "  - 利用类实现\n",
    "\n",
    "### 4.6.1 简单函数装饰器\n",
    "\n",
    "- Python装饰器（Decorator）是对函数或方法的修饰\n",
    "- 利用装饰器，能够在不侵入代码的情况下为函数或方法动态地添加新的功能\n",
    "- 类型\n",
    "  - 基于函数的装饰器\n",
    "  - 基于类的装饰器"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 函数装饰器的实现利用了函数的对象特征，以及嵌套函数或闭包的运行思想\n",
    "- 使用形式\n",
    "\n",
    "```\n",
    "@装饰器\n",
    "def 函数():\n",
    "    ... ...\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 一个能够输出函数的运行时间的装饰器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "def run_time(fun):\n",
    "    def wrapper():\n",
    "        start = time.time()\n",
    "        result = fun()\n",
    "        end = time.time()\n",
    "        print(f'函数{fun.__name__}的运行时间为{(end-start):.4}秒')\n",
    "        return result\n",
    "    return wrapper"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 装饰器的名字就是定义的嵌套函数中外层函数的名字\n",
    "- 由于装饰器没有侵入定义函数的代码，因此在被修饰函数内部感知不到装饰器的存在"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "@run_time\n",
    "def fun1():\n",
    "    for _ in range(10):\n",
    "        time.sleep(0.1)\n",
    "\n",
    "@run_time\n",
    "def fun2():\n",
    "    for _ in range(10):\n",
    "        time.sleep(0.2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "- 装饰器同样不会侵入调用函数的代码，因此经过装饰器修饰的函数在调用时与普通函数没有任何区别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "函数fun1的动行时间为1.031秒\n"
     ]
    }
   ],
   "source": [
    "fun1()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "函数fun2的动行时间为2.02秒\n"
     ]
    }
   ],
   "source": [
    "fun2()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### 4.6.2 函数装饰器的工作原理\n",
    "\n",
    "#### 装饰器的实际执行过程\n",
    "\n",
    "- 函数装饰器只是一种令代码更加简洁的语法糖\n",
    "  - 下面的例子实现了与装饰器完全相同的功能"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fun1():\n",
    "    for _ in range(10):\n",
    "        time.sleep(0.1)\n",
    "\n",
    "def fun2():\n",
    "    for _ in range(10):\n",
    "        time.sleep(0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "函数fun1的动行时间为1.033秒\n"
     ]
    }
   ],
   "source": [
    "f1 = run_time(fun1)\n",
    "f1()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "函数fun2的动行时间为2.034秒\n"
     ]
    }
   ],
   "source": [
    "f2 = run_time(fun2)\n",
    "f2()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "__两种方法是等价的，__\n",
    "__装饰器的优势是完全不必改变任何函数定义或调用的代码逻辑，就能够为函数增加新的功能或行为__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "#### 装饰器的运行时机\n",
    "\n",
    "- 装饰器的执行过程包括如下几个步骤\n",
    "  - 定义装饰器\n",
    "  - 定义函数\n",
    "  - 装饰函数\n",
    "  - 调用装饰之后的函数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- 它们的运行顺序是怎样的呢？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "将下面的代码保存为一个脚本文件`run_chance.py`\n",
    "\n",
    "```python\n",
    "def run_chance(fun):\n",
    "    print(f'装饰函数 {fun.__name__}')\n",
    "    return fun\n",
    "\n",
    "@run_chance\n",
    "def fun1():\n",
    "    print('运行函数fun1')\n",
    "\n",
    "@run_chance\n",
    "def fun2():\n",
    "    print('运行函数fun2')\n",
    "\n",
    "if __name__ == '__main__': \n",
    "    fun1()\n",
    "    fun2()\n",
    "\n",
    "```\n",
    "\n",
    "在终端运行`python run_chance.py`，输出结果为：\n",
    "\n",
    "```\n",
    "$ python run_chance.py\n",
    "装饰函数 fun1\n",
    "装饰函数 fun2\n",
    "运行函数fun1\n",
    "运行函数fun2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "装饰器对函数的修饰不是在函数调用时执行，而是在函数定义时就执行的"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 在其他模块中导入被装饰器修饰的函数时\n",
    "\n",
    "```python\n",
    "from run_chance import *\n",
    "```\n",
    "输出结果为：\n",
    "```\n",
    "装饰函数 fun1\n",
    "装饰函数 fun2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "结果表明，装饰器在导入模块时就被执行了"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "#### 装饰器与闭包的关系\n",
    "- 装饰器就是闭包\n",
    "  - 装饰器外层函数的参数为函数\n",
    "  - 返回为内层定义的函数\n",
    "  - 内层函数中引用了外层中的形参变量"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### 4.6.3 函数装饰器的优化\n",
    "\n",
    "#### 含参函数的装饰\n",
    "\n",
    "- 修饰函数包含参数，则需要内层函数参够处理这些参数\n",
    "  - 利用函数的可变参数方便地实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "def run_time(fun):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        start = time.time()\n",
    "        result = fun(*args, **kwargs)\n",
    "        end = time.time()\n",
    "        print(f'函数{fun.__name__}的动行时间为{(end-start):.4}秒')\n",
    "        return result\n",
    "    return wrapper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "@run_time\n",
    "def fun1():\n",
    "    for _ in range(10):\n",
    "        time.sleep(0.1)\n",
    "\n",
    "@run_time\n",
    "def fun2(t):\n",
    "    for _ in range(t):\n",
    "        time.sleep(0.1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "函数fun1的动行时间为1.032秒\n"
     ]
    }
   ],
   "source": [
    "fun1()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "函数fun2的动行时间为1.034秒\n"
     ]
    }
   ],
   "source": [
    "fun2(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "#### 被修饰函数的元信息\n",
    "\n",
    "- 经过修饰的函数与被修饰函数并非同一个函数\n",
    "  - 函数的元信息丢失，例如`__name__`以及`__doc__`等"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'wrapper'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fun1.__name__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'wrapper'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fun2.__name__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 为了保留函数的元信息，需要在装饰器定义时手动地将被修饰函重要的元信息保存至内层函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "def run_time(fun):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        start = time.time()\n",
    "        result = fun(*args, **kwargs)\n",
    "        end = time.time()\n",
    "        print(f'函数{fun.__name__}的动行时间为{(end-start):.4}秒')\n",
    "        return result\n",
    "    wrapper.__name__ = fun.__name__\n",
    "    wrapper.__doc__ = fun.__doc__\n",
    "    return wrapper\n",
    "\n",
    "@run_time\n",
    "def fun():\n",
    "    for _ in range(10):\n",
    "        time.sleep(0.1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'fun'"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fun.__name__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 使用`functools.wraps`装饰器实现元信息的复制\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "from functools import wraps\n",
    "\n",
    "def run_time(fun):\n",
    "    @wraps(fun)\n",
    "    def wrapper(*args, **kwargs):\n",
    "        start = time.time()\n",
    "        result = fun(*args, **kwargs)\n",
    "        end = time.time()\n",
    "        print(f'函数{fun.__name__}的动行时间为{(end-start):.4}秒')\n",
    "        return result\n",
    "    return wrapper\n",
    "\n",
    "@run_time\n",
    "def fun():\n",
    "    for _ in range(10):\n",
    "        time.sleep(0.1)\n",
    "    print('fun')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'fun'"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fun.__name__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 利用`functools.update_wrapper`函数实现元信息的复制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "from functools import update_wrapper\n",
    "\n",
    "def run_time(fun):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        start = time.time()\n",
    "        result = fun(*args, **kwargs)\n",
    "        end = time.time()\n",
    "        print(f'函数{fun.__name__}的动行时间为{(end-start):.4}秒')\n",
    "        return result\n",
    "    return update_wrapper(wrapper, fun)\n",
    "\n",
    "@run_time\n",
    "def fun():\n",
    "    for _ in range(10):\n",
    "        time.sleep(0.1)\n",
    "    print('fun')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `__wrapped__`属性\n",
    "  - 使用`wraps`装饰器或`update_wrapper`函数之后，可以通过被修饰函数的`__wrapped__`属性获得原始函数的引用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'fun'"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fun.__wrapped__.__name__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "fun\n"
     ]
    }
   ],
   "source": [
    "fun.__wrapped__()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.6.4 装饰器的叠加*\n",
    "\n",
    "#### 叠加装饰器的定义与使用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "def dec1(fun):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        print('dec1')\n",
    "        return fun(*args, **kwargs)\n",
    "    return wrapper\n",
    "\n",
    "def dec2(fun):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        print('dec2')\n",
    "        return fun(*args, **kwargs)\n",
    "    return wrapper\n",
    "\n",
    "@dec1\n",
    "@dec2\n",
    "def fun():\n",
    "    print('fun')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dec1\n",
      "dec2\n",
      "fun\n"
     ]
    }
   ],
   "source": [
    "fun()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "#### 叠加装饰器的原理\n",
    "\n",
    "- 函数叠加使用多个装饰器修饰时，其作用原理与单个装饰器完全相同\n",
    "  - 只不过，外层装饰器的修饰对象并不是函数，而是内层装饰器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "def dec1(fun):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        print('dec1')\n",
    "        return fun(*args, **kwargs)\n",
    "    return wrapper\n",
    "\n",
    "def dec2(fun):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        print('dec2')\n",
    "        return fun(*args, **kwargs)\n",
    "    return wrapper\n",
    "\n",
    "def fun():\n",
    "    print('fun')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dec1\n",
      "dec2\n",
      "fun\n"
     ]
    }
   ],
   "source": [
    "dec1(dec2(fun))()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "#### 叠加装饰器的执行顺序\n",
    "\n",
    "- 被修饰函数调用之前的代码先执行\n",
    "  - 执行顺序为先外层后内层\n",
    "- 接下来执行被修饰函数\n",
    "- 最后执行被修饰函数之后的代码\n",
    "  - 执行顺序为先内层后外层"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "from functools import wraps\n",
    "\n",
    "def dec1(fun):\n",
    "    @wraps(fun)\n",
    "    def wrapper(*args, **kwargs):\n",
    "        print('dec1 before ...')\n",
    "        result = fun(*args, **kwargs)\n",
    "        print('dec1 after ...')\n",
    "        return result\n",
    "    return wrapper\n",
    "\n",
    "def dec2(fun):\n",
    "    @wraps(fun)\n",
    "    def wrapper(*args, **kwargs):\n",
    "        print('dec2 before ...')\n",
    "        result = fun(*args, **kwargs)\n",
    "        print('dec2 after ...')\n",
    "        return result\n",
    "    return wrapper\n",
    "\n",
    "@dec1\n",
    "@dec2\n",
    "def fun():\n",
    "    print('完成fun的功能')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dec1 before ...\n",
      "dec2 before ...\n",
      "完成fun的功能\n",
      "dec2 before ...\n",
      "dec1 after ...\n"
     ]
    }
   ],
   "source": [
    "fun()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.6.5 含参装饰器\n",
    "\n",
    "- 装饰器实际上是一种高阶函数\n",
    "  - 函数可以有参数，因此装饰器也可以有参数\n",
    "- 定义带参数的装饰器需要使用一个三层的嵌套函数\n",
    "  - 最外层的函数称为装饰器工厂函数\n",
    "  - 内部的两层函数是真正的装饰器定义"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "def param_dec(arg1, arg2): \n",
    "    def dec(fun):\n",
    "        def wrapper(*args, **kw):\n",
    "            print(f\"before actions based on {arg1} and {arg2} ...\")\n",
    "            result = fun(*args, **kw)\n",
    "            print(f\"after actions based on {arg1} and {arg2} ...\")\n",
    "            return result\n",
    "        return wrapper\n",
    "    return dec\n",
    "\n",
    "@param_dec('arg1', 'arg2')\n",
    "def fun():\n",
    "    print('完成fun的功能')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "before actions based on arg1 and arg2 ...\n",
      "完成fun的功能\n",
      "after actions based on arg1 and arg2 ...\n"
     ]
    }
   ],
   "source": [
    "fun()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 能够根据参数将函数运行时间的单位显示为秒、毫秒或者微秒的装饰器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "from datetime import datetime\n",
    "from functools import wraps\n",
    "\n",
    "def run_time(unit):\n",
    "    def dec(fun):\n",
    "        @wraps(fun)\n",
    "        def wrapper(*args, **kwargs):\n",
    "            start = datetime.now()\n",
    "            result = fun(*args, **kwargs)\n",
    "            end = datetime.now()\n",
    "            if unit == 'ms':\n",
    "                time_str = f'{(end - start).total_seconds()*1000:.0f}毫秒'\n",
    "            elif unit == 'us':\n",
    "                time_str = f'{(end - start).total_seconds()*10**6:.0f}微秒'\n",
    "            else:\n",
    "                time_str = f'{(end - start).total_seconds():.0f}秒'\n",
    "            print(f'函数{fun.__name__}的动行时间为{time_str}')\n",
    "            return result\n",
    "        return wrapper\n",
    "    return dec"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "@run_time('s')\n",
    "def fun1():\n",
    "    for _ in range(10):\n",
    "        time.sleep(0.1)\n",
    "\n",
    "@run_time('ms')\n",
    "def fun2():\n",
    "    for _ in range(10):\n",
    "        time.sleep(0.1)\n",
    "\n",
    "@run_time('us')\n",
    "def fun3():\n",
    "    for _ in range(10):\n",
    "        time.sleep(0.1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "函数fun1的动行时间为1秒\n"
     ]
    }
   ],
   "source": [
    "fun1()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "函数fun2的动行时间为1034毫秒\n"
     ]
    }
   ],
   "source": [
    "fun2()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "函数fun3的动行时间为1037261微秒\n"
     ]
    }
   ],
   "source": [
    "fun3()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.6.6 函数装饰器应用实例 *\n",
    "\n",
    "- 利用装饰器及函数参数的类型注解来实现类型检查"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "from inspect import signature\n",
    "from functools import wraps\n",
    "\n",
    "def type_check(fun):\n",
    "    @wraps(fun)\n",
    "    def wrapper(*args, **kwargs):\n",
    "        sig = signature(fun)          # 函数的签名\n",
    "        param_dict = sig.parameters   # 函数的{参数: 类型}字典\n",
    "        param_list = list(param_dict.values())\n",
    "        for i, k in enumerate(args):  # 检查位置参数\n",
    "            assert type(k) is param_list[i].annotation,\\\n",
    "                f'第{i+1}个参数的类型必须为{param_list[i].annotation}'\n",
    "        for k, v in kwargs.items():   # 检查关键字参数\n",
    "            assert type(v) is param_dict[k].annotation, \\\n",
    "                f'参数{k}的类型必须为{param_dict[k].annotation}'\n",
    "        return fun(*args, **kwargs)\n",
    "    return wrapper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "@type_check\n",
    "def fun(x: int, y: float):\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "ename": "AssertionError",
     "evalue": "第2个参数的类型必须为<class 'float'>",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mAssertionError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-44-3f43dc183e44>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mfun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m<ipython-input-42-2b636f173ed3>\u001b[0m in \u001b[0;36mwrapper\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m      9\u001b[0m         \u001b[0mparam_list\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mlist\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mparam_dict\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mvalues\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     10\u001b[0m         \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mk\u001b[0m \u001b[0;32min\u001b[0m \u001b[0menumerate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m  \u001b[0;31m# 检查位置参数\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 11\u001b[0;31m             \u001b[0;32massert\u001b[0m \u001b[0mtype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mk\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mparam_list\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mannotation\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;31m\\\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     12\u001b[0m                 \u001b[0;34mf'第{i+1}个参数的类型必须为{param_list[i].annotation}'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     13\u001b[0m         \u001b[0;32mfor\u001b[0m \u001b[0mk\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mv\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mkwargs\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mitems\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m   \u001b[0;31m# 检查关键字参数\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mAssertionError\u001b[0m: 第2个参数的类型必须为<class 'float'>"
     ]
    }
   ],
   "source": [
    "fun(1, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "ename": "AssertionError",
     "evalue": "第1个参数的类型必须为<class 'int'>",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mAssertionError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-45-be3945dfd467>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mfun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1.0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m<ipython-input-42-2b636f173ed3>\u001b[0m in \u001b[0;36mwrapper\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m      9\u001b[0m         \u001b[0mparam_list\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mlist\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mparam_dict\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mvalues\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     10\u001b[0m         \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mk\u001b[0m \u001b[0;32min\u001b[0m \u001b[0menumerate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m  \u001b[0;31m# 检查位置参数\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 11\u001b[0;31m             \u001b[0;32massert\u001b[0m \u001b[0mtype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mk\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mparam_list\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mannotation\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;31m\\\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     12\u001b[0m                 \u001b[0;34mf'第{i+1}个参数的类型必须为{param_list[i].annotation}'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     13\u001b[0m         \u001b[0;32mfor\u001b[0m \u001b[0mk\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mv\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mkwargs\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mitems\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m   \u001b[0;31m# 检查关键字参数\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mAssertionError\u001b[0m: 第1个参数的类型必须为<class 'int'>"
     ]
    }
   ],
   "source": [
    "fun(1.0, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [
    {
     "ename": "AssertionError",
     "evalue": "参数y的类型必须为<class 'float'>",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mAssertionError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-46-85690ed67ee6>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mfun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m<ipython-input-42-2b636f173ed3>\u001b[0m in \u001b[0;36mwrapper\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m     12\u001b[0m                 \u001b[0;34mf'第{i+1}个参数的类型必须为{param_list[i].annotation}'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     13\u001b[0m         \u001b[0;32mfor\u001b[0m \u001b[0mk\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mv\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mkwargs\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mitems\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m   \u001b[0;31m# 检查关键字参数\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 14\u001b[0;31m             \u001b[0;32massert\u001b[0m \u001b[0mtype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mv\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mparam_dict\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mk\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mannotation\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;31m \u001b[0m\u001b[0;31m\\\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     15\u001b[0m                 \u001b[0;34mf'参数{k}的类型必须为{param_dict[k].annotation}'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     16\u001b[0m         \u001b[0;32mreturn\u001b[0m \u001b[0mfun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mAssertionError\u001b[0m: 参数y的类型必须为<class 'float'>"
     ]
    }
   ],
   "source": [
    "fun(1, y=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "fun(1, 2.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### 4.6.7 重要的 Python 内置装饰器 *\n",
    "\n",
    "#### `lru_cache`\n",
    "\n",
    "- 将被修饰函数的运行结果缓存起来，后续调用的时候如果函数参数与已缓存结果的参数相同，则不再执行函数，直接将缓存的结果返回"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "计算 1 的平方\n",
      "1\n",
      "1\n",
      "1\n",
      "1\n",
      "1\n"
     ]
    }
   ],
   "source": [
    "from functools import lru_cache\n",
    "\n",
    "@lru_cache\n",
    "def fun(i):\n",
    "    print(f'计算 {i} 的平方')\n",
    "    return i**2\n",
    "\n",
    "for _ in range(5):\n",
    "    print(fun(1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `lru_cache`的参数\n",
    "  - `maxsize`：缓存的大小\n",
    "  - `typed`：缓存结果会考虑参数的数据类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [],
   "source": [
    "from functools import lru_cache\n",
    "@lru_cache(typed=True)\n",
    "def fun(i):\n",
    "    print(f'计算 {i} 的平方')\n",
    "    return i**2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "计算 1 的平方\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fun(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "计算 1.0 的平方\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1.0"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fun(1.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `lru_cache`的缓存是利用字典来实现的\n",
    "  - 字典的键基于被修饰函数的参数来构建的\n",
    "  - 求被修饰函数的参数必须是可哈希的（hashable）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "from functools import lru_cache\n",
    "@lru_cache(10)\n",
    "def average(values):\n",
    "    n = len(values)\n",
    "    return sum(values)/n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.0"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "average((1, 2, 3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "unhashable type: 'list'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-55-5e145017fa0a>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0maverage\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m: unhashable type: 'list'"
     ]
    }
   ],
   "source": [
    "average([1, 2, 3])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "#### `singledispatch`\n",
    "\n",
    "- 使用`singledispatch`装饰器可实现类似于函数重载的功能"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [],
   "source": [
    "from functools import singledispatch\n",
    "\n",
    "@singledispatch\n",
    "def average(data):\n",
    "    n = len(data)\n",
    "    return sum(data)/n\n",
    "\n",
    "@average.register(dict)   # 参数为字典时\n",
    "def _(data):\n",
    "    data = data.values()\n",
    "    n = len(data)\n",
    "    return sum(data)/n\n",
    "\n",
    "@average.register(str)    # 参数为字符串时\n",
    "def _(data):\n",
    "    data = [float(i) for i in data.split(',')]\n",
    "    n = len(data)\n",
    "    return sum(data)/n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.0"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "average([1, 2, 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.0"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "average({'a': 1, 'b': 2, 'c': 3})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.0"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "average('1, 2, 3')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `singledispatch`将被修饰函数转变成一个名为`xxx.register`的装饰器\n",
    "- 与使用`xxx.register`修饰的一组函数被绑定在一起，组成了一个泛函数（Generic Function）\n",
    "- 当调用函数的时候，会根据参数的类型确定被实际被调用的函数\n",
    "- 被`xxx.register`修饰的函数名字是无关紧要的，因此常使用`_`来替代"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## 4.7 常用函数编程工具*\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.7.1 常用工具函数\n",
    "\n",
    "- `functools.partial`\n",
    "  - 固定一个函数的部分参数值，返回一个以其余参数为参数的可调用对象"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "函数`fun`是以a、b、c为参数的一元二次函数$ax^2+bx+c$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fun(a, b, c, x):\n",
    "    return a*x**2 + b*x +c"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "利用`partial`将参数a、b、c固定为1、2、3，返回的$f$表示$x^2+2x+3$。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "from functools import partial\n",
    "f = partial(fun, 1, 2, 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "38"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `map`与`filter`\n",
    "  - `map`函数的作用是将一个函数作用于可迭代对象中的每一个元素之上，并返回由每个元素的运算结果构成的新的可迭代对象\n",
    "  - `filter`的作用是对可迭代对象的元素进行过滤"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 16, 4, 64, 25, 49]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lst = [1, 4, 2, 8, 5, 7]\n",
    "lst_square = map(lambda x: x**2, lst)\n",
    "list(lst_square)\n",
    "[1, 16, 4, 64, 25, 49]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[4, 2, 8]"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lst_f = filter(lambda x: x%2==0, lst)\n",
    "list(lst_f)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `functools.reduce`\n",
    "  - 函数`fun`必须接受两个参数，并返回一个值\n",
    "  - 它首先接受可迭代对象的前两个元素A和B，并计算`fun(A, B)`，然后处理第三个元素C，计算`fun(fun(A, B), C)`，以次类推直至将可迭代对象中的元素处理完毕\n",
    "  - `functools.reduce`返回最后一次`fun`的执行结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2240"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from functools import reduce\n",
    "lst = [1, 4, 2, 8, 5, 7]\n",
    "reduce(lambda r, e: r * e, lst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `any`和`all`\n",
    "  - 检查一个可迭代对象的逻辑值，并返回`True`或`False`\n",
    "  - `any`在可迭代对象中的任意元素的逻辑值为真时返回`True`\n",
    "  - `all`则在所有元素的逻辑值都为真时返回`True`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lst = [1, 4, 2, 8, 5, 7, 0]\n",
    "any(lst)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "all(lst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.7.2 `operator`模块\n",
    "-  `operator`模块中包含了一系列对应于 Python 运算符的函数\n",
    "  - 数学运算： `add`，`sub`，`mul`，`truediv`,`floordiv`；\n",
    "  - 逻辑运算： `not_`，`truth`；\n",
    "  - 比较运算： `eq`，`ne`，`lt`，`le`，`gt`， `ge`。\n",
    "  - 对象确认： `is_`，`is_not`。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.7.3 `itertools`模块\n",
    "\n",
    "| 函数                | 功能描述                                  |\n",
    "| :------------------- | :----------------------------------------- |\n",
    "| `count(start,step)` | 创建一个从`start`开始，步长为`step`的可迭代对象 |\n",
    "| `cycle(iter)`                  | 创建一个将可迭代对象`iter`重复无限多次的可迭代对象 |\n",
    "|`repeat(elem, [n]) `| 创建一个将元素`elem`重复`n`次的可迭代对象，`n`为空时重复无限多次 |\n",
    "|`chain(iterA, iterB, ...) `| 将多个可迭代对象拼接起来生成一个新的可迭代对象 |\n",
    "|`islice(iter, [start], stop, [step])`| 截取`iter`的部分元素构成新的可迭代对象 |\n",
    "|`tee(iter, [n])`| 将可迭代对象`iter`复制`n`次，`n`默认值为2 |\n",
    "|`starmap(func, iter) `|`iter`为以元组为元素的可迭代对象，`starmap`以`iter`的元素作为函数`func`的参数，返回`func`的执行结果构成的可迭代对象|\n",
    "|`filterfalse(predicate, iter)`| 与`filter`函数相反，返回所有让 `predicate` 返回` False` 的元素 |\n",
    "|`takewhile(predicate, iter) `|返回一直让 `predicate `返回 `True` 的元素，一旦 `predicate` 返回 `False`就终止迭代|\n",
    "|`dropwhile(predicate, iter)`| 与`takewhile`相反，当` predicate `返回`True` 的时候丢弃元素，返回可迭代对象的其余元素 |\n",
    "|`compress(data, selectors)`| 返回`data`中`selectors`为`True`的相应位置的元素 |\n",
    "|`groupby(iter,key_func=None)`| 以`key_func`对`iter`中元素的处理结果为key，对`iter`中的元素进行分组 |\n"
   ]
  }
 ],
 "metadata": {
  "author": "liuchen",
  "celltoolbar": "幻灯片",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.1"
  },
  "rise": {
   "enable_chalkboard": true,
   "footer": "",
   "progress": true,
   "scroll": true,
   "slideNumber": true
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  },
  "url": "https://github.com/hitlic/python_book"
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
